package com.wf.apicommons.handler;



import com.fasterxml.jackson.databind.ObjectMapper;
import com.wf.apicommons.utils.CodeEnum;
import com.wf.apicommons.utils.CommonResult;
import com.wf.apicommons.utils.MD5Util;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @Description: JWT验证拦截器
 */
public class JWTInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        CommonResult<String> result=new CommonResult<>();

        //获取请求来源
        String requestSource = request.getHeader("RequestSource");
        boolean decrypt = MD5Util.verifyingCiphertext(requestSource,"request_from_gateway");
        //验证请求来源是否为网关转发
        if(decrypt){
            //放行请求
            return true;
        }else{
            result.setCode(CodeEnum.ILLEGAL_REQUEST.getCode());
            result.setData(CodeEnum.ILLEGAL_REQUEST.getMessage());
        }

        //将map转化成json，response使用的是Jackson
        String json = new ObjectMapper().writeValueAsString(result);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin","*");
        response.getWriter().print(json);
        return false;
    }
}
